package com.tiancheng.trade.settlement.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiancheng.trade.commom.core.utils.ServiceLocator;


/**
 * json util
 *
 * @author kellen
 * @date 2019/12/30
 */
public final class JsonUtil {

    private static ObjectMapper objectMapper = ServiceLocator.getBean(ObjectMapper.class);

    /**
     * 序列化对象
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 反序列化json
     *
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr, clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
